<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class gettvzing extends CI_Controller {

	var $theme_data = array(
			'layout_main' => 'maccuoi_layout',
			'right' => 'widget/right',
		);
	var $cookieFileName = 'cookie.txt';
	var $userName = 'danquangninh1405';
	var $password = 'rock8learn';
	var $category = array(
		array(
			'id'=>'2',
			'maxpage'=>'7',
			'link'=>'http://tv.zing.vn/the-loai/Tieu-Pham-Hai/IWZ9ZIII.html',
		),array(
			'id'=>'3',
			'maxpage'=>'2',
			'link'=>'http://tv.zing.vn/the-loai/San-Khau-Liveshow-Hai/IWZ9ZIIW.html',
		),array(
			'id'=>'4',
			'maxpage'=>'8',
			'link'=>'http://tv.zing.vn/the-loai/Giai-Tri-Vui-Nhon/IWZ9ZIIO.html',
		),
	
	);
	function __construct() {
        parent::__construct();
		//$this->load->model("getsite/tvzing");
		$this->load->model('mgetsite');
		$this->load->library('get_data_html');
		$this->cookieFileName = dirname (realpath(__FILE__)).'/'.$this->cookieFileName; 
		set_time_limit(9999999999);
    }
	function index($page = 1) {
        $data = array();
        
		
        //$this->theme_data["main"] = "home";
        // $data["seo"] = $this->seo->get('trang-chu', $page);
       // $this->template->view($this->theme_data, $data);
    }
	function getMaxPageProgram($catUrl = ''){
	 $html_content = $this->get_data_html->get_content($catUrl);
	$page = $this->get_data_html->GetBetween($html_content, '<div class="paging">', '</div>');
		$arr_page = explode("<li>",$page);
		$arr_page = end($arr_page);
		$page = $this->get_data_html->GetBetween($arr_page, 'href="', '"');
		$page = explode("p=",$page);
		$maxpage = end($page);
		return ($maxpage >1)?$maxpage:1;
	}
	function insertall(){
	
		foreach($this->category as $cate){
			if($cate['maxpage'] >1){
				for($page=1; $page<=$cate['maxpage']; $page++){
					$this->getProgram($cate['link'],$cate['id'],$page);
					sleep(1);
				}
			}
		}
	}
	
	function getProgram($catUrl,$catID,$page = 0){
	
	//$catUrl = 'http://tv.zing.vn/the-loai/Giai-Tri-Vui-Nhon/IWZ9ZIIO.html';
	//$catID = 4;
	if($page >1){
		$catUrl.= '?sort=new&p='.$page;
	}
		echo '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />';
        $list = array();
        $html_content = $this->get_data_html->get_content($catUrl);
		$array = array('type' => '1',
            'estart' => '<div class="box-description">',
            'eend' => '<div class="info-detail">',
        );
		 
		$videos =array();
        $html = $this->get_data_html->load($html_content, $array);
		 for ($i = count($html) - 1; $i >= 0; $i--) {
            $t_list = array();
            $html_content = $html[$i];

            //Link  
            $link = $this->get_data_html->GetBetween($html_content, ' href="', '"');
            $link = trim(strip_tags($link));
			
			$title = trim(strip_tags($html_content));
			$datainsert = array(
                'GET_LINK' => $link,
                'PROG_TITLE' => $title,
            );
            $list[] = $datainsert;
            unset($datainsert);
		}
		$arr_data = array();
		for($i=0; $i<count($list); $i++){
			$url = 'http://tv.zing.vn'.$list[$i]['GET_LINK'];
			$html_content = $this->get_data_html->get_content($url);
			
			$description = $this->get_data_html->GetBetween($html_content, '<p id="_description" class="rows2" expand="rows2">', '</p>');
			
			$cover = $this->get_data_html->GetBetween($html_content, '<div class="fluid-img">', '</a>');
			$cover = $this->get_data_html->GetBetween($cover, 'src="', '"');
			
			$thumb = $this->get_data_html->GetBetween($html_content, '<div class="outside-des">', '<div class="box-description">');
			$thumb = $this->get_data_html->GetBetween($thumb, 'src="', '"');
			$tags = get_meta_tags($url,true);
			$arr_data = array(
				'GET_LINK'=>$url,
				'CAT_ID'=>$catID,
				'PROG_STATUS'=>1,
				'PROG_TITLE'=>$list[$i]['PROG_TITLE'],
				'PROG_DESCRIPTION'=>trim($description),
				'PROG_THUMB'=>trim($thumb),
				'PROG_COVER'=>trim($cover),
				'SEO_DESCRIPTION'=>trim($tags['description']),
				'SEO_METATITLE'=>$list[$i]['PROG_TITLE'],
				'SEO_KEYWORD'=>trim($tags['keywords']),
				'SEO_H1'=>$list[$i]['PROG_TITLE'],
			);
		echo "insert progam: ".$arr_data['PROG_TITLE']."<br>";
		$progamID = $this->mgetsite->insert_program($arr_data);

		//get series
		$array = array('type' => '1',
            'estart' => '<div class="section row126">',
            'eend' => '<!-- END.section -->',
        );
        $shtml = $this->get_data_html->load($html_content, $array);
		
		
		for($j=0; $j<count($shtml); $j++){
			$shtml_content =$shtml[$j];
			$videos = array();
			$series = $this->get_data_html->GetBetween($shtml_content, '<div class="title-bar group">', '</h3>');
			$checkLink = $this->get_data_html->GetBetween($series, 'href="', '"');
			if($checkLink){
				$checkLink = 'http://tv.zing.vn'.$checkLink;
			}
			$stitle = trim(strip_tags($series));
			$arr_series = array(
				'GET_PROG_ID'=>$progamID,
				'SER_TITLE'=>$stitle,
				'GET_LINK'=>@$checkLink,
			);
			//echo "insert series: ".$arr_series['SER_TITLE']."<br>";
			$seriesID = $this->mgetsite->insert_series($arr_series);
			
			//if có link series
			if($checkLink){
				$videos = $this->getSeries($checkLink, $seriesID);
			}
			else {
			
					$array = array('type' => '1',
						'estart' => '<div class="subtray flex-des">',
						'eend' => '<!-- END .description -->',
					);
				$series_html = $this->get_data_html->load($shtml_content, $array);
				
				//get video
					foreach($series_html as $r){
						$vlink = $this->get_data_html->GetBetween($r, 'href="', '"');
						
						$vthumb = $this->get_data_html->GetBetween($r, 'src="', '"');
						
						$vtitle  = $this->get_data_html->GetBetween($r, '<h4 class="title">', '</h4>');
						$vtitle = trim(strip_tags($vtitle));
						
						$vtime  = $this->get_data_html->GetBetween($r, '<div class="info-video">', '</div>');
						$vtime = trim(strip_tags($vtime));
						$vtime = strtotime($vtime);
						
						$videos[] = array(
							'GET_LINK' => 'http://tv.zing.vn'.$vlink,
							'VID_TITLE' => $vtitle,
							'VID_THUMB' => $vthumb,
							'VID_TIME' => $vtime,
							'GET_SER_ID' => $seriesID,
						);
				 
					}
				}
				if(count($videos)>0){
				foreach($videos as $video){
					echo "insert video: ".$video['VID_TITLE']."<br>";
					$this->mgetsite->insert_video($video);
				}
				}
			}
		}
		
		return $arr_data;
	}
	
	function getSeries($url = '',$seriesID = 0){
		// $url = 'http://tv.zing.vn/series/Cac-Tieu-Pham-Trich-Doan-Dac-Sac';
		 $maxPage = $this->getMaxPageProgram($url);
		 $list = array();
		
		for($page=1; $page<= $maxPage; $page++) {
		$getUrl = $url.'?p='.$page;
		 
		$array = array('type' => '1',
            'estart' => '<div class="item">',
            'eend' => '<!--END .item-->',
        );
		echo '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />';
		
        $html_content = $this->get_data_html->get_content($getUrl);
        $html = $this->get_data_html->load($html_content, $array);

	
		 for ($i = count($html) - 1; $i >= 0; $i--) {
            $t_list = array();
            $html_content = $html[$i];

            //Link  
            $link = $this->get_data_html->GetBetween($html_content, 'href="', '"');
            $link = trim(strip_tags($link)); 
			
			//thumb  
            $thumb = $this->get_data_html->GetBetween($html_content, 'src="', '"');
            $thumb = trim(strip_tags($thumb));

			$title =$this->get_data_html->GetBetween($html_content, '<div class="box-description">', '</h3>');
			$title = trim(strip_tags($title));
			
			$vtime  = $this->get_data_html->GetBetween($html_content, '<i class="icon-clock">', '</span>');
			$vtime = trim(strip_tags($vtime));
			$vtime = strtotime($vtime);

			$datainsert = array(
                'GET_LINK' => 'http://tv.zing.vn'.$link,
                'VID_TITLE' => $title,
                'VID_THUMB' => $thumb,
                'VID_TIME' => $vtime,
                'GET_SER_ID' => $seriesID,
            );
            $list[] = $datainsert;
            unset($datainsert);
		}
	}
		return $list;
	}
	
	
	function trans(){
		$this->load->model("mprogram");
		$this->load->model("mseries");
		$this->load->model("mvideo");
		echo '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />';
		$programs = $this->db->get("tv_program")->result();
		foreach($programs as $program){
			$progamID = 0;
			$getProgramID = $program->GET_ID;
			if($program->PROG_ID == 0){
				$programInsert = $program;
				unset($programInsert->PROG_ID);
				unset($programInsert->GET_ID);
				unset($programInsert->GET_LINK);
				$programInsert = (array)$programInsert;
				$progamID = $this->mprogram->insert($programInsert);
				echo "trans series: ".$program->PROG_TITLE."<br>";
				$this->db->where("GET_ID",$getProgramID);
				$this->db->update("tv_program",array('PROG_ID'=>$progamID));
				
			}
			else {
				$progamID = $program->PROG_ID;
			}
			
			$this->db->where("GET_PROG_ID",$getProgramID);
			$series = $this->db->get("tv_series")->result();
			foreach($series as $serie){
				$serieGetID = $serie->GET_ID;
				$serieSerID = $serie->SER_ID;
				if($serie->SER_ID == 0){
					$serieInsert = $serie;
					
					$serieInsert->PROG_ID = $progamID;
					unset($serieInsert->SER_ID);
					unset($serieInsert->GET_ID);
					unset($serieInsert->GET_LINK);
					unset($serieInsert->GET_PROG_ID);
					$serieInsert = (array)$serieInsert;
					$serieID = $this->mseries->insert($serieInsert);
					$this->db->where("GET_ID",$serieGetID);
					$this->db->update("tv_series",array('SER_ID'=>$serieID));
					echo "trans series: ".$serie->SER_TITLE."<br>";
				}
				else {
					$serieID = $serieSerID;
				}
				$this->db->where("GET_SER_ID",$serieGetID);
				$videos = $this->db->get("tv_video")->result();
				foreach($videos as $video){
					$getVideoID = $video->GET_ID;
					if($video->VID_ID == 0){
						$videoInsert = $video;
						
						$videoInsert->VID_LINK = $videoInsert->GET_LINK;
						$videoInsert->SER_ID = $serieID;
						unset($videoInsert->VID_ID);
						unset($videoInsert->GET_ID);
						unset($videoInsert->GET_LINK);
						unset($videoInsert->GET_SER_ID);
						$videoInsert = (array)$videoInsert;
						$videoID = $this->mvideo->insert($videoInsert);
						
						$this->db->where("GET_ID",$getVideoID);
						$this->db->update("tv_video",array('VID_ID'=>$videoID));
					}
				}
			}
	 
		}
	}
	
	function login() {
	/*
	$url = 'https://sso3.zing.vn/login';
	$api = $this->getAPIKey();
	$data = "u=".$this->userName."&p=".$this->password."&x=45&y=28&u1=http://id.mp3.zing.vn/sns/sso3?f=3U9FGM10004&cbfunction=loginCallback&pid=38&fp=http://id.mp3.zing.vn/sns/sso3?f=3U9FGM10004&cbfunction=loginCallback&apikey=".$api;
	$dk = '';
	 // $dk = $this->postPage($url,$data, '', '');
	 */
	$new_cookie = "#HttpOnly_.zing.vn	TRUE	/	FALSE	0	zsid	kAVH.103726519.25454.jZRScO4bt7CscF9rWINSSu0JiQeUy81JW8iq9D91t7g19Tn1i1plHB0Tx4QF9Tnp\n";
	//$new_cookie = "#HttpOnly_.zing.vn	TRUE	/	FALSE	0	zsid	K-46.102275260.33.Y5LGGhxnuwS2QVkXll7ZfnKEpn55yoaVlwqcIEoLuw2-yUEKYiVRbeZ7xQS\n";
 
		$filenum=@fopen($this->cookieFileName,"w");
		flock($filenum,LOCK_EX);
		$file_data=fwrite($filenum,$new_cookie);
		fclose($filenum);
	/*
	#HttpOnly_.zing.vn	TRUE	/	FALSE	0	zsid	tsEE.103726519.6035.lavLjhbHv0SExCe1kL7a1nAkm8H2Kow_k2qgwEirv0wvKUGrY6ZNC8Xfr3AqKUG7
	*/
	
	// echo  $dk;
	 $xml =  $this->getPage("http://tv.zing.vn/tv/xml/media/kHJmyWAzpSTbCsnyyvHLn",'',100,'');
	 
	 $xml = @simplexml_load_string($xml);

		//foreach($xml->item->attributes()->flv[0] as $r){
		$t = (array)$xml->item->attributes();
		print_r($xml);
		//}
	}
	
	function getAPIKey(){
		$html = file_get_contents("http://login.me.zing.vn/");
		$apiKey = $this->get_data_html->GetBetween($html,'name="apikey" value="','"');
		return $apiKey;
	} 
	
	function postPage($url,$pvars,$referer,$timeout){

    if(!isset($timeout))
        $timeout=30;
    $curl = curl_init();
    $post = $pvars;
    if(isset($referer)){
        curl_setopt ($curl, CURLOPT_REFERER, $referer);
    }
    curl_setopt ($curl, CURLOPT_URL, $url);
    curl_setopt ($curl, CURLOPT_COOKIEJAR, $this->cookieFileName);
    curl_setopt ($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt ($curl, CURLOPT_USERAGENT, sprintf("Mozilla/%d.0",rand(4,5)));
    curl_setopt ($curl, CURLOPT_HEADER, TRUE);
    curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt ($curl, CURLOPT_POST, 1);
    curl_setopt ($curl, CURLOPT_POSTFIELDS, $post);
    curl_setopt ($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/x-www-form-urlencoded"));
    $html = curl_exec ($curl);
    curl_close ($curl);
    return $html;
}

function getPage($url, $referer, $timeout, $header){
    if(!isset($timeout))
        $timeout=30;
    $curl = curl_init();
    if(strstr($referer,"://")){
        curl_setopt ($curl, CURLOPT_REFERER, $referer);
    }
    curl_setopt ($curl, CURLOPT_URL, $url);
    curl_setopt ($curl, CURLOPT_COOKIEFILE, $this->cookieFileName);
    curl_setopt ($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt ($curl, CURLOPT_USERAGENT, sprintf("Mozilla/%d.0",rand(4,5)));
   // curl_setopt ($curl, CURLOPT_HEADER, (int)$header);
    curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
    $html = curl_exec ($curl);
    curl_close ($curl);
    return $html;
}

function encode(){
$kz_crypt = new KZ_Crypt;

$kz_crypt->_text = 'ABC';

//Bắt đầu mã hoá.
if($kz_crypt->_encrypt() != false){
    //Kết quả trả về.
    echo $kz_crypt->_result;
}
}

	function decode($text = ''){
	$kz_crypt = new KZ_Crypt;

	$kz_crypt->_text = $text;

		//Bắt đầu giải mã.
		if($kz_crypt->_decrypt() != false){
			//Kết quả trả về.
			return $kz_crypt->_result;
		}
	}
}

class KZ_Crypt {

    public $_text = '';
    
    //Chìa khoá để mở kho báu ^^
    public $_key = 'f_pk_ZingTV_1_@z';
    public $_iv = 'f_iv_ZingTV_1_@z';
    
    //Kết quả trả về
    public $_result = '';
    
    /**
     * Hàm mã hoá
    **/
    public function _encrypt(){
        if($this->_text != ''){
            $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
            $iv_size = mcrypt_enc_get_iv_size($cipher);
            if (mcrypt_generic_init($cipher, $this->_key, $this->_iv) != -1){
                $cipherText = mcrypt_generic($cipher,$this->_text);
                mcrypt_generic_deinit($cipher);
                $this->_result = bin2hex($cipherText);
                return true;
            }
        }else{
            return false;
        }
    }
    
    /**
     * Hàm giải mã
    **/
    public function _decrypt(){
        if($this->_text != ''){
            $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
            $iv_size = mcrypt_enc_get_iv_size($cipher);
            if(mcrypt_generic_init($cipher, $this->_key, $this->_iv) != -1){
                $cipherText = mdecrypt_generic($cipher,$this->_hexToString($this->_text));
                mcrypt_generic_deinit($cipher);
                $this->_result = $cipherText;
                return true;
            }else{
                return false;
            }
        }
    }
    
    /**
     * Hàm chuyển đổi từ mã hex sang chuỗi.
    **/
    protected function _hexToString($hex){
        if(!is_string($hex)){
            return null;
        }
        $char = '';
        for($i=0; $i<strlen($hex);$i+=2){
            $char .= chr(hexdec($hex{$i}.$hex{($i+1)}));
        }
        return $char;
    }
}